﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="AttributeProviderExtensions.cs" company="JDML Consulting Ltd.">
//   Copyright 2011 Photon Project - http://photon.codeplex.com
// </copyright>
// <summary>
//   Attribute extensions
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace Photon.Reflection
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Reflection;

    /// <summary>
    /// Attribute extensions
    /// </summary>
    public static class AttributeProviderExtensions
    {
        /// <summary>
        /// Retrieves a custom attribute of type <typeparamref name="TAttribute"/> from the specified <paramref name="provider"/>
        /// </summary>
        /// <typeparam name="TAttribute">The type of the attribute.</typeparam>
        /// <param name="provider">The provider.</param>
        /// <param name="inherted">When <c>true</c>look up the heirarchy chain for the custom attribute.</param>
        /// <returns>A reference to the single custom attribute of type attributeType that is applied to element, or a null 
        /// reference if there is no such attribute.</returns>
        /// <exception cref="AmbiguousMatchException">More than one of the requested attributes was found.</exception>
        public static TAttribute GetCustomAttribute<TAttribute>(this ICustomAttributeProvider provider, bool inherted = false) where TAttribute : Attribute
        {
            var attributes = provider.GetCustomAttributes(typeof(TAttribute), inherted);
            if (attributes.Length > 1)
            {
                throw new AmbiguousMatchException();
            }

            return attributes.Length > 0 ? (TAttribute)attributes[0] : null; 
        }

        /// <summary>
        /// Retrieves a custom attributes of type <typeparamref name="TAttribute"/> from the specified <paramref name="provider"/>
        /// </summary>
        /// <typeparam name="TAttribute">The type of the attribute.</typeparam>
        /// <param name="provider">The provider.</param>
        /// <param name="inherted">if set to <c>true</c> [inherted].</param>
        /// <returns></returns>
        public static IEnumerable<TAttribute> GetCustomAttributes<TAttribute>(this ICustomAttributeProvider provider, bool inherted) where TAttribute : Attribute
        {
            return provider.GetCustomAttributes(typeof(TAttribute), inherted).Cast<TAttribute>();
        }
    }
}
